package com.chrudgames.stayintouch;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
 
public class DatabaseHandler extends SQLiteOpenHelper {
 
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
 
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
 
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
 
    // Contacts Table Columns names
    private static final String KEY_ID = "_id";
    private static final String KEY_FREQUENCY = "frequency";
    private static final String KEY_LAST = "last";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    private static final String KEY_PHOTO = "photo";
 
   

    
    
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
 
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
   
    	   	     	
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
        		+ KEY_ID + " STRING," + KEY_FREQUENCY + " INTEGER,"
                + KEY_LAST + " DATE," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT," + KEY_PHOTO + " TEXT)";
        
            
        
        db.execSQL(CREATE_CONTACTS_TABLE);

       // db.close();
    }
 
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
     
        onCreate(db);
    }
 
 
    void runQuery(String ssql) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL(ssql);
        db.close();
    }
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
 
    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_FREQUENCY, KEY_LAST,
                KEY_NAME, KEY_PH_NO, KEY_PHOTO }, KEY_ID + "=?",
                new String[] { contact.getID() }, null, null, null, null);
        if (cursor.getCount() == 0) {
       
          ContentValues values = new ContentValues();
        values.put(KEY_ID, contact.getID()); // Contact Name
        values.put(KEY_FREQUENCY, contact.getFrequency()); // Contact Phone
        values.put(KEY_LAST, contact.getLast().toString()); // Contact Name
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
        values.put(KEY_PHOTO, contact.getPhoto()); // Contact Phone
 
        
        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        cursor.close();
        db.close(); // Closing database connection

        }else{
        	//Log.w("onActivityResult", "Update");
        	updateContact(contact);
        }
        
        
    }
 
    // Getting single contact
    Contact getContact(String id) {
        SQLiteDatabase db = this.getReadableDatabase();
 
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_FREQUENCY, KEY_LAST, KEY_NAME, KEY_PH_NO, KEY_PHOTO }, KEY_ID + "=?",
                new String[] { id }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
 
        Contact contact = new Contact(cursor.getString(0), Integer.parseInt(cursor.getString(1)),
                Date.valueOf(cursor.getString(2)), cursor.getString(3), cursor.getString(4), cursor.getInt(5));
        // return contact
        cursor.close();
        db.close();
        
        return contact;
    }
 
    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
 
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
 
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(cursor.getString(0));
                contact.setFrequency(Integer.parseInt(cursor.getString(1)));
                contact.setLast(Date.valueOf(cursor.getString(2)));
                contact.setName(cursor.getString(3));
                contact.setPhoneNumber(cursor.getString(4));
                contact.setPhoto(cursor.getInt(5));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
 
        cursor.close();
        db.close();
        // return contact list
        return contactList;
    }
 
    public Cursor getContactCursor(String id) {

	   	
        // Select All Query
        String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " where _id='" + id +"'";
        SQLiteDatabase db = this.getWritableDatabase();
 
        Cursor cursor = db.rawQuery(selectQuery, null);

        return cursor;
      

    }
    
    public Cursor getAllContactsCursor() {
    	
      	
        // Select All Query
        String selectQuery = "SELECT *, cast(julianday(Date('now')) - julianday(Last) as integer) as dDays, " 
       + " (julianday(Date('now')) - julianday(Last))/frequency*100 as precMax FROM " + TABLE_CONTACTS + " where _id <> '" + getID().toString() + "' order by name";
        
       // String selectQuery = "SELECT *, 'Last contact: ' || julianday(Date('now')) - julianday(Last) || ' days ago' as dDays, " 
       // 	       + " (julianday(Date('now')) - julianday(Last))/frequency*100 as precMax FROM " + TABLE_CONTACTS + " order by name";
        
        SQLiteDatabase db = this.getWritableDatabase();
 
        Cursor cursor = db.rawQuery(selectQuery, null);

        return cursor;
      

    }
    
    public Cursor getAllDueContactsCursor() {

	   	
        // Select All Query
        String selectQuery = "SELECT name FROM " + TABLE_CONTACTS + " where (julianday(Date('now')) - julianday(last)) > frequency ";
        SQLiteDatabase db = this.getWritableDatabase();
 
        Cursor cursor = db.rawQuery(selectQuery, null);

        return cursor;
    }
    
    
    // Updating single contact
    public int updateContact(Contact contact) {
        
    	int intUpdate;
    	
    	
    	SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_ID, contact.getID());
        values.put(KEY_FREQUENCY, contact.getFrequency());
        values.put(KEY_LAST, contact.getLast().toString());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PHOTO, contact.getPhoto());

        
        intUpdate = db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { contact.getID() });
        db.close();		
        // updating row
        return intUpdate;
        
    }
 
    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { contact.getID() });
        db.close();
    }
 
    public String getID() {
    	
    	String strID = "42" + Build.BOARD.length()%10+ Build.BRAND.length()%10 +
    			Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
    			Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
    			Build.TAGS.length()%10 + Build.TYPE.length()%10 +
            	Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
            	Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
            	Build.USER.length()%10 ; //13 digits
    	
    	return strID.toString();
      	
    	
    }

    
    public boolean owned() {
    	
    	boolean bolOwned;
    	
    	bolOwned = false;
    	
        String countQuery = "SELECT _id FROM " + TABLE_CONTACTS + " where _id = " + getID();

        SQLiteDatabase db = this.getReadableDatabase();
  
        Cursor cursor = db.rawQuery(countQuery, null);
//        cursor.close();
        
        // return count
        if(cursor.getCount()>0) bolOwned = true;
        
        cursor.close();
        
        return bolOwned;
    	    	
    }
    
    // Getting contacts Count
    public int getContactsCount() {

    	int count;
    	
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getReadableDatabase();
  
        Cursor cursor = db.rawQuery(countQuery, null);
//      
        count = cursor.getCount();
        cursor.close();

        return count;
      
    }
 
    public Date getTodaysDate() {

    	Calendar c = Calendar.getInstance();
        
        int month = c.get(Calendar.MONTH) + 1;
        String sDate =  c.get(Calendar.YEAR) + "-" + month + "-" + c.get(Calendar.DAY_OF_MONTH);
               
        Date dDate = Date.valueOf(sDate);
        
        // return count
        return dDate;
    }
    
}